//
//  RestApi.swift
//  SwiftSign
//
//  Created by continue on 2021/4/26.
//

import Foundation
import RxSwift
import RxCocoa
import ObjectMapper
import Moya
import Moya_ObjectMapper
import Alamofire

typealias MoyaError = Moya.MoyaError

enum ApiError: Error {
    case serverError(response: ErrorResponse)
}

class RestApi: SwiftSignAPI {

    let signProvider: SignNetworking
    
    init(signProvider: SignNetworking) {
        self.signProvider = signProvider
    }

}

extension RestApi {
    func userInit() -> Single<UserInitInfo> {
        return self.requestObject(.userInit, type: UserInitInfo.self)
    }
    func getRandUser() -> Single<RandUserInfo> {
        return self.requestObject(.getRandUser, type: RandUserInfo.self)
    }
    func userRegister(username: String, password: String) -> Single<UserInfo> {
        return self.requestObject(.userRegiter(username: username, password: password), type: UserInfo.self)
    }
    func phoneLoginSendCode(phone: String) -> Single<Code> {
        return self.requestObject(.loginSendCode(phone: phone), type: Code.self)
    }
    func phoneLogin(phone: String, code: String) -> Single<UserInfo> {
        return self.requestObject(.phoneLogin(phone: phone, code: code), type: UserInfo.self)
    }
}


extension RestApi {
    private func requestObject<T: BaseMappable>(_ target: SignAPI, type: T.Type) -> Single<T> {
            return signProvider.request(target)
                .mapObject(T.self, atKeyPath: "data")
                .observeOn(MainScheduler.instance).asSingle()
        }
//    private func requestObject<T: BaseMappable>(_ target: SignAPI, type: T.Type) -> Single<T> {
//        return moyaProvider.rx.request(target)
//            .filterSuccessfulStatusCodes()
//            .mapObject(T.self)
//            .observeOn(MainScheduler.instance)
//    }
}


